<?php
/**
 * @author GhostWei
 * @date 2012-5-31
 */
class picture_category_localeConcept extends system_concept_abstract {

	protected $_lang = null;
	public function __construct($lang = null) {
		$this->_lang = $lang;
		parent::__construct(array(), array());
	}
	
	public function init() {
		$this->setRowClass('picture_category_row');
		$this->setModel('picture_category_model', 'category');
		$this->setModelCols('category', array('id', 'parent_id', 'name', 'cover'));
		$this->setModelCols('category', array('display_order', 'is_recommend', 'is_active', 'creationtime', 'lastmodified'));
	}

	public function save($row) {
		if(!preg_match('#[^\\\/\?\|\#]{2,50}#is', $row->getName())) {
			throw new picture_exception("Key Name formation error.");
		}		
		$row->set('parent_id', intval($row->getParentId()));
		$row->set('display_order', intval($row->getDisplayOrder()));
		$row->setIsActive(($row->get('is_active') ? 1 : 0));
		$row->setIsRecommend(($row->get('is_recommend') ? 1 : 0));

		/**
		 * 因为special ID 有变化，所以这里要先取到locale的完事row
		 * 不可以修改顺序
		 */
		$locale = $row->getLocale();
		if(!$locale->getTitle()) {
			throw new picture_exception("Title can not be empty.");
		}
		if($row->getId()) {
			if($this->getModel('category')->fetchRow(array('id != ?' => $row->getId(), 'name = ?' => $row->getName()))) {
				throw new picture_exception("This Category is already Existing.");
			}
	 		$row->setLastmodified(system_date::timestamp());
			$this->getModel('category')->update($row->getModelData('category'), array('id = ?' => $row->getId()));
		} else {
			if(!($eRow = $this->getModel('category')->fetchRow(array('name = ?' => $row->getName())))) {
				$row->setLastmodified(system_date::timestamp());
				$row->setCreationtime(system_date::timestamp());
				$id = $this->getModel('category')->insert($row->getModelData('category'));
				$row->setId($id);
			} else {
				$row->setId($eRow['id']);
			}
		}
		/**
		 * 用前面取到的 locale row
		 */
		$locale->setCategoryId($row->getId());
		$locale->save();
		return $row;
	}

	protected $_locale = null;
	public function getLocale($row, $lang = null) {
		if($lang !== null) $this->_lang = $lang;
		if($this->_locale === null || $this->_locale->getCategoryId() != $row->getId()) {
			$concept = new picture_category_locale_concept();
			if(!($this->_locale = $concept->fetch(array('category_id = ?' => intval($row->getId()), 'lang = ?' => $this->_lang)))) {
				$this->_locale = $concept->create();
				$this->_locale->setLang($this->_lang);
				$this->_locale->setCategoryId(intval($row->getId()));
			}
		}
		return $this->_locale;
	}
	
	public function delete($row) {
		return;
	}

}
